package com.coai.procurement.service

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.stereotype.Service

/**
 * 智能采购服务
 * 
 * 提供采购管理的AI功能：
 * - 需求预测（时间序列分析）
 * - 供应商评估（多维度评分）
 * - 合同分析（NLP条款提取）
 * 
 * @property kafkaTemplate Kafka消息发送模板
 */
@Service
class ProcurementService(
    private val kafkaTemplate: KafkaTemplate<String, Any>
) {
    
    /**
     * AI需求预测
     */
    /**
     * AI需求预测
     * 
     * 基于历史销售数据预测未来需求
     * 考虑因素：历史趋势、季节性、增长率
     * 
     * @param productId 产品ID
     * @param days 预测天数
     * @return 需求预测结果
     */
    suspend fun forecastDemand(
        productId: String,
        days: Int
    ): DemandForecast = withContext(Dispatchers.IO) {
        
        // 基于历史数据的AI需求预测
        try {
            // 模拟时间序列分析
            // TODO: 实际应该使用ARIMA或LSTM模型进行预测
            
            // 1. 获取历史销售数据
            val historicalSales = getHistoricalSales(productId, 90) // 过90天数据
            
            // 2. 计算趋势
            val avgDailySales = historicalSales.average()
            val recentAvg = historicalSales.takeLast(7).average()
            val trend = when {
                recentAvg > avgDailySales * 1.2 -> "INCREASING"
                recentAvg < avgDailySales * 0.8 -> "DECREASING"
                else -> "STABLE"
            }
            
            // 3. 应用季节性因子
            val seasonalFactor = calculateSeasonalFactor()
            
            // 4. 预测未来需求
            val predictedQuantity = (avgDailySales * days * seasonalFactor).toInt()
            val confidence = calculateConfidence(historicalSales)
            
            DemandForecast(
                productId = productId,
                predictedQuantity = predictedQuantity,
                confidence = confidence,
                trend = trend
            )
        } catch (e: Exception) {
            logger.error("Failed to forecast demand", e)
            DemandForecast(productId, 1000, 0.5, "UNKNOWN")
        }
    }
    
    private fun getHistoricalSales(productId: String, days: Int): List<Double> {
        // 模拟历史销售数据
        return (1..days).map { 100.0 + (it % 30) * 5.0 + Math.random() * 20 }
    }
    
    private fun calculateSeasonalFactor(): Double {
        // 模拟季节性因子
        val month = java.time.LocalDate.now().monthValue
        return when (month) {
            11, 12 -> 1.5  // 旺季
            1, 2 -> 0.8    // 淡季
            else -> 1.0
        }
    }
    
    private fun calculateConfidence(data: List<Double>): Double {
        if (data.isEmpty()) return 0.5
        
        val mean = data.average()
        val variance = data.map { (it - mean) * (it - mean) }.average()
        val stdDev = Math.sqrt(variance)
        val cv = stdDev / mean  // 变异系数
        
        return (1.0 - cv.coerceIn(0.0, 1.0)).coerceIn(0.5, 0.95)
    }
    
    /**
     * AI供应商评估
     */
    /**
     * 供应商多维度评估
     * 
     * 从多个维度评估供应商表现：
     * - 交货率：40%权重
     * - 质量评分：40%权重
     * - 价格竞争力：20%权重
     * 
     * @param supplierId 供应商ID
     * @return 评估结果和推荐等级
     */
    suspend fun evaluateSupplier(supplierId: String): SupplierEvaluation = withContext(Dispatchers.IO) {
        
        // 多维度供应商评估
        try {
            // TODO: 实际应该从数据库获取供应商历史数据
            
            // 1. 获取供应商历史数据
            val deliveryRecords = getDeliveryRecords(supplierId)
            val qualityRecords = getQualityRecords(supplierId)
            val priceRecords = getPriceRecords(supplierId)
            
            // 2. 计算各维度分数
            val deliveryScore = calculateDeliveryScore(deliveryRecords)
            val qualityScore = calculateQualityScore(qualityRecords)
            val priceScore = calculatePriceScore(priceRecords)
            
            // 3. 加权汇总（交货:40%, 质量:40%, 价格:20%）
            val overallScore = deliveryScore * 0.4 + qualityScore * 0.4 + priceScore * 0.2
            
            // 4. 生成推荐等级
            val recommendation = when {
                overallScore >= 0.9 -> "HIGHLY_RECOMMENDED"
                overallScore >= 0.8 -> "RECOMMENDED"
                overallScore >= 0.7 -> "ACCEPTABLE"
                else -> "NOT_RECOMMENDED"
            }
            
            SupplierEvaluation(
                supplierId = supplierId,
                overallScore = overallScore,
                deliveryScore = deliveryScore,
                qualityScore = qualityScore,
                priceScore = priceScore,
                recommendation = recommendation
            )
        } catch (e: Exception) {
            logger.error("Failed to evaluate supplier", e)
            SupplierEvaluation(supplierId, 0.5, 0.5, 0.5, 0.5, "UNKNOWN")
        }
    }
    
    private fun getDeliveryRecords(supplierId: String): List<DeliveryRecord> {
        // 模拟交货记录
        return (1..10).map {
            DeliveryRecord(onTime = Math.random() > 0.1)
        }
    }
    
    private fun getQualityRecords(supplierId: String): List<QualityRecord> {
        return (1..10).map {
            QualityRecord(defectRate = Math.random() * 0.05)
        }
    }
    
    private fun getPriceRecords(supplierId: String): List<PriceRecord> {
        return (1..10).map {
            PriceRecord(price = 100.0 + Math.random() * 20, marketAvg = 110.0)
        }
    }
    
    private fun calculateDeliveryScore(records: List<DeliveryRecord>): Double {
        return records.count { it.onTime }.toDouble() / records.size
    }
    
    private fun calculateQualityScore(records: List<QualityRecord>): Double {
        val avgDefectRate = records.map { it.defectRate }.average()
        return (1.0 - avgDefectRate * 10).coerceIn(0.0, 1.0)
    }
    
    private fun calculatePriceScore(records: List<PriceRecord>): Double {
        val avgPrice = records.map { it.price }.average()
        val marketAvg = records.first().marketAvg
        return (marketAvg / avgPrice).coerceIn(0.5, 1.0)
    }
    
    /**
     * AI合同分析
     */
    /**
     * 合同智能分析
     * 
     * 使用NLP技术分析合同内容：
     * - 提取关键条款（价格、交期、质量等）
     * - 识别风险条款
     * - 生成优化建议
     * 
     * @param contractContent 合同文本内容
     * @return 分析结果，包含关键条款、风险和建议
     */
    suspend fun analyzeContract(contractContent: String): ContractAnalysis = withContext(Dispatchers.IO) {
        
        // NLP合同条款提取
        try {
            // TODO: 实际应该使用NLP模型进行合同分析
            
            val keyTerms = mutableListOf<String>()
            val risks = mutableListOf<String>()
            val suggestions = mutableListOf<String>()
            
            // 1. 关键词提取
            if (contractContent.contains("价格") || contractContent.contains("金额")) {
                keyTerms.add("价格条款")
            }
            if (contractContent.contains("交期") || contractContent.contains("交付")) {
                keyTerms.add("交期条款")
            }
            if (contractContent.contains("质量") || contractContent.contains("标准")) {
                keyTerms.add("质量标准")
            }
            if (contractContent.contains("违约") || contractContent.contains("赔偿")) {
                keyTerms.add("违约赔偿")
            }
            if (contractContent.contains("保密")) {
                keyTerms.add("保密条款")
            }
            
            // 2. 风险识别
            if (contractContent.contains("违约金")) {
                val hasHighPenalty = contractContent.contains("万") || contractContent.contains("千")
                if (hasHighPenalty) {
                    risks.add("违约金较高，建议审慎评估")
                }
            }
            if (contractContent.contains("不可抗力")) {
                if (!contractContent.contains("免责")) {
                    risks.add("不可抗力条款不明确")
                }
            }
            if (contractContent.contains("永久") || contractContent.contains("无限期")) {
                risks.add("存在无限期条款，需谨慎")
            }
            
            // 3. 生成建议
            if (keyTerms.contains("交期条款")) {
                suggestions.add("建议明确交付时间和延迟赔偿")
            }
            if (!keyTerms.contains("质量标准")) {
                suggestions.add("建议添加详细的质量验收标准")
            }
            if (!contractContent.contains("争议解决")) {
                suggestions.add("建议添加争议解决机制")
            }
            
            ContractAnalysis(
                keyTerms = keyTerms,
                risks = risks,
                suggestions = suggestions
            )
        } catch (e: Exception) {
            logger.error("Failed to analyze contract", e)
            ContractAnalysis(
                keyTerms = listOf("解析失败"),
                risks = listOf("无法识别风险"),
                suggestions = listOf("建议人工审查")
            )
        }
    }
}

data class DeliveryRecord(val onTime: Boolean)
data class QualityRecord(val defectRate: Double)
data class PriceRecord(val price: Double, val marketAvg: Double)

data class DemandForecast(
    val productId: String,
    val predictedQuantity: Int,
    val confidence: Double,
    val trend: String
)

data class SupplierEvaluation(
    val supplierId: String,
    val overallScore: Double,
    val deliveryScore: Double,
    val qualityScore: Double,
    val priceScore: Double,
    val recommendation: String
)

data class ContractAnalysis(
    val keyTerms: List<String>,
    val risks: List<String>,
    val suggestions: List<String>
)
